package Pattern.CommandPattern.Program2;

class Light { //电灯类
    public void turnLight(int degree) {//调整灯光亮度，0表示关灯，100表示亮度最大}
    }

    static class TV { //电视机类
        public void setChannel(int channel) {//0表示关机，1表示开机并切换到1频道}
        }

        interface Command { //抽象命令类
            void on();

            void off();
        }

        static class RemoteController { //遥控器类
            //遥控器有4个按钮，按照编号分别对应4个Command对象
            protected Command[] commands = new Command[4];

            //按钮被按下时执行命令对象中的命令
            public void onPressButton(int button) {
                if (button % 2 == 0) {
                    commands[button].on();
                }
                else commands[button].off();
            }

            public void setCommand(int button, Command command) {
                /*(1)*/
                commands[button] = command; //设置每个按钮对应的命令对象
            }
        }

        static class LightCommand implements Command {  //电灯命令类
            protected Light light; //指向要控制的电灯对象

            public void on() {
                light.turnLight(100);
                System.out.println("Light On!");
            }

            public void off() {
                light.turnLight(0); /* (2) */
                System.out.println("Light Off!");
            }

            public LightCommand(Light light) {
                this.light = light;
            }
        }

        static class TVCommand implements Command { //电视机命令类
            protected TV tv;

            public void on() {
                tv.setChannel(1); //(3);
                System.out.println("TV On!\nChannel1 right now!");
            }

            public void off() {
                tv.setChannel(0);
                System.out.println("TV Off!");
            }

            public TVCommand(TV tv) {
                this.tv = tv;
            }
        }

        static class Test {
            public static void main(String args[]) {
                //创建电灯和电视对象
                Light light = new Light();
                TV tv = new TV();
                LightCommand lightCommand = new LightCommand(light);
                TVCommand tvCommand = new TVCommand(tv);
                RemoteController remoteController = new RemoteController();
                //设置按钮和命令对象
                remoteController.setCommand(0, lightCommand/*(4)*/);
                remoteController.setCommand(1, lightCommand/*(4)*/);
                remoteController.setCommand(2, tvCommand/*(4)*/);
                remoteController.setCommand(3, tvCommand/*(4)*/);
                remoteController.onPressButton(2);
                //此处省略设置按钮1、按钮2和按钮3的命令对象代码
            }
        }
    }
}

